package com.example.day16;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    PullToRefreshListView listV;
    MyAdapter myAdapter;
    LinearLayout linearLayout;
    List<Map<String,Object>> dataList;
    MyHandler myHandler =new MyHandler(this);
    int page=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listV = findViewById(R.id.list1);
        linearLayout = findViewById(R.id.over);
        dataList = new ArrayList<Map<String, Object>>();

        //listV.setMode(Mode.PULL_FROM_END);//只支持上拉
        //listV.setMode(Mode.PULL_FROM_START);//只支持下拉
        listV.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
        listV.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载");
        listV.getLoadingLayoutProxy(false, true).setRefreshingLabel("加载中");
        listV.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多数据");

        getDate(20,page,100);
        listV.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {  //注意这里用的2
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                Toast.makeText(getApplicationContext(), "下拉刷新", Toast.LENGTH_LONG).show();
                //时间
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);//加上时间
                page=1;
                getDate(20,page,100); // 下拉刷新
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                Toast.makeText(getApplicationContext(), "上拉获取更多", Toast.LENGTH_LONG).show();
                page++;
                getDate(20,page,200);  // 加载更多
            }

        });

    }

    private void getDate(int limit,int page,int what){
        Message message = Message.obtain();
        message.what = what;
        HashMap<String, String> map = new HashMap<>();
        map.put("stage_id", 1 + "");
        map.put("limit", limit + "");
        map.put("page", page + "");
        new WorkThread(WorkThread.STIRING, myHandler, message, "http://www.qubaobei.com/ios/cf/dish_list.php", map).start();

    }

    private static class MyHandler extends Handler {
        private WeakReference<Context> reference;   //


        public MyHandler(Context context) {
            reference = new WeakReference<>(context);//这里传入activity的上下文
        }
        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = (MainActivity) reference.get();
            super.handleMessage(msg);
            switch (msg.what) {      //判断标志位
                case 100:
                    if( msg.obj!=null) {
                        String jsonStr = msg.obj.toString();
                        Log.e("jsonSTR", jsonStr);
                        try {
                            JSONObject json = new JSONObject(jsonStr);
                            JSONArray jsA = json.getJSONArray("data");
                            int length = jsA.length();
                            activity.dataList.clear();
                            for (int i = 0; i < length; i++) {
                                Map<String, Object> map = new HashMap<>();
                                JSONObject jsobj = jsA.getJSONObject(i);
                                map.put("title", jsobj.getString("title"));
                                map.put("food_str", jsobj.getString("food_str"));
                                map.put("pic", jsobj.getString("pic"));
                                activity.dataList.add(map);
                                Log.e("jsonD", i + "");
                            }
                            activity.myAdapter = new MyAdapter(activity, activity.dataList);
                            activity.listV.setAdapter(activity.myAdapter);
                            activity.listV.onRefreshComplete();  //完成
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 200:
                    if( msg.obj!=null) {
                        String jsonStr = msg.obj.toString();
                        Log.e("jsonSTR", jsonStr);
                        try {
                            JSONObject json = new JSONObject(jsonStr);
                            JSONArray jsA = json.getJSONArray("data");
                            int length = jsA.length();
                            if(length<=0){
                                activity.page--;
                            }else{
                                for (int i = 0; i < length; i++) {
                                    Map<String, Object> map = new HashMap<>();
                                    JSONObject jsobj = jsA.getJSONObject(i);
                                    map.put("title", jsobj.getString("title"));
                                    map.put("food_str", jsobj.getString("food_str"));
                                    map.put("pic", jsobj.getString("pic"));
                                    activity.dataList.add(map);
                                    Log.e("jsonD", i + "");
                                }
                            }
                            activity.listV.onRefreshComplete();  //完成

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }

        }
    }
    private void missHand(){
        Log.e("#####","缩");
        myHandler.post(new Runnable() {
            @Override
            public void run() {
//                listV.smoothScrollToPosition(1);
            }
        });

    }
}
